# coding=utf-8
import pymongo


class DBConnection(object):
    """数据库操作类"""

    def __init__(self, db_name, collection_name):
        self.db_name = db_name
        self.collection_name = collection_name
        self.collection = None

    def connection(self):
        """数据库连接"""
        connection = pymongo.MongoClient('localhost', 27017)
        db = connection[self.db_name]
        self.collection = db[self.collection_name]

    def get_all(self):
        """
        从数据库中获取所有新闻
        :return: 新闻内容
        """
        return list(self.collection.find())

    def get_news_content(self, news_id):
        """
        由新闻id从数据库中获取到新闻内容
        :param news_id: 新闻id号（list）
        :return: 新闻内容
        """
        news_content = []
        for id in news_id:
            news_content.append(self.collection.find({'news_id': id})[0]['news_content'])
        return news_content

    def get_news_time(self, news_id):
        """
        由新闻id获取新闻时间
        :param news_id: 新闻id号（list）
        :return: news_time 新闻发布时间
        """
        news_time = []
        for id in news_id:
            news = self.collection.find({'news_id': id})
            time = news[0]['news_pub_time']
            news_time.append(time[6:10] + '/' + time[0:2] + '/' + time[3:5] + ' ' + time[10:])
        return news_time

    def get_comment_num(self, news_id):
        """
        由新闻id获取新闻评论数
        :param news_id: 新闻id号（list）
        :return: comment_num 评论数
        """
        comment_num = []
        for id in news_id:
            news = self.collection.find({'news_id': id})
            comment_num.append(news[0]['news_comment_num'])
        return comment_num

    def get_news_title(self, news_id):
        """
        由新闻id获取新闻评论数
        :param news_id: 新闻id号（list）
        :return: comment_num 评论数
        """
        news_title = []
        for id in news_id:
            news = self.collection.find({'news_id': id})
            news_title.append(news[0]['news_title'])
        return news_title